# -*- coding: utf-8 -*-  
__author__ = 'hftec'
import socket
import simplejson
import fcntl
import struct
import threading, time

def get_ip_address(ifname):
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    	return socket.inet_ntoa(fcntl.ioctl(
      		  s.fileno(),
        		0x8915,  # SIOCGIFADDR
        		struct.pack('256s', ifname[:15]))[20:24])

class UdpServer:

    def __init__(self):
        self.udp_data = threading.Thread(target = self.wait_data)
	self.udp_data.start()
    def wait_data(self):
        while(True):
            try:
		address = ('', 8089)
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		s.bind(address)
		print "udp server"
		while True:
    			data, addr = s.recvfrom(2048)
    			if not data:
        			print "client has exist"
        			break
    			print "received:", data, "from", addr
    			json = simplejson.loads(data)
   			if (json["cmd"] == 1):
        			json["data"] = get_ip_address("eth0")
				print "json",json
        			s.sendto(simplejson.dumps(json),addr)

		s.close()
            except:
                s.close()
                return

